<script setup>
// import { ElMessage } from 'element-plus'
import { reactive } from 'vue'
import { tableOptions } from './config'
import { validate } from './validate'
import axios from 'axios'
const value1 = ref(false)
let tableData = ref({})
let newTableData = {}
const getData = async () => {
  axios('/assets/data.json').then(({ data }) => {
    tableData.value = data
    console.log(tableData, 999)
    newTableData = data
  })
}
getData()

// const tableData = reactive({ ...tableDatas })

// const newTableData = readonly({ ...tableData })
// const newTableData = JSON.parse(JSON.stringify({ ...tableData }))

let finArr = {}
let rules = {}
const tableRefs = ref([])
const scrollToBottom = (tableRef, index) => {
  nextTick(() => {
    if (tableRef) {
      tableRef.setScrollTop(index * 67)
    }
  })
}

const add = (key, index) => {
  let obj = {}
  if (!tableData['value'][key]) {
    tableData['value'][key] = []
  }
  if (!finArr[key]) {
    finArr[key] = []
  }
  tableOptions[key].tableColumn.forEach((item) => {
    obj[item.key] = item[item.key]
    // console.log(obj, item.key, 89)
    obj['delabled'] = true
    rules[item.key] = validate(item.validate)
  })

  finArr[key].push(obj)
  tableData['value'][key].push(obj)
  // 滚动到底部
  scrollToBottom(tableRefs['value'][index], finArr[key].length)
}
const formRefs = ref([])
const handle = () => {
  let isAllValid = true
  const promises = formRefs.value.map((form, index) => {
    return new Promise((resolve) => {
      form.validate((valid) => {
        if (!valid) {
          isAllValid = false
        }
        resolve(valid)
      })
    })
  })
  // 等待所有表单校验完成
  Promise.all(promises).then((results) => {
    isAllValid = results.every((valid) => valid)
    if (isAllValid) {
      console.log(finArr, '所有的校验成功,finArr:提交的参数')
      // 提交所有表单数据的逻辑,这里可以发送异步请求了
      // 初始化
      // finArr = {}
      // tableData = newTableData
    } else {
      console.error('校验不成功')
      ElMessage.error('表单校验不成功')
    }
  })
}

const changeHandle = (e) => {
  if (!e) {
    getData()
    finArr = {}
    // console.log(newTableData, 777)
    // tableData = newTableData // 模拟数据，应该是发送请求重新获取
  }
}

const delHandle = (key, index) => {
  tableData['value'][key] && tableData['value'][key].splice(index, 1)
  finArr[key] && finArr[key].splice(index - newTableData[key].length, 1)
}
</script>
<template>
  <div>
    <div>
      <el-switch v-model="value1" @change="changeHandle" />
      <!-- <el-button type="primary" v-if="value1" @click="add">添加</el-button> -->
    </div>
    <template v-for="(item1, key1, index1) in tableOptions" :key="item1.name">
      <h1>
        {{ item1.tableName }}
        <el-button
          type="primary"
          v-if="value1 && item1.addShow"
          @click="add(key1, index1)"
          >添加</el-button
        >
      </h1>

      <el-table
        max-height="250"
        border
        :data="tableData[key1]"
        style="width: 100%"
        stripe
        ref="tableRefs"
      >
        <el-table-column
          align="center"
          :label="item2.label"
          :prop="item2.key"
          v-for="(item2, index2) in item1.tableColumn"
          :key="index2"
          show-overflow-tooltip
        >
          <template #default="scope">
            <template v-if="scope.row.id"> {{ scope.row[item2.key] }}</template>
            <el-form
              v-else
              :model="scope.row"
              :rules="rules"
              style="max-width: 600px"
              ref="formRefs"
            >
              <el-form-item :prop="item2.key" v-if="item2.type == 'select'">
                <el-select
                  v-model="scope.row[item2.key]"
                  :placeholder="item2.validate ? '必选' : '可选'"
                  style="width: 240px"
                >
                  <el-option
                    v-for="(item3, index3) in item2.selectOption"
                    :key="index3"
                    :label="item3.label"
                    :value="item3.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item :prop="item2.key" v-else>
                <el-input
                  v-model="scope.row[item2.key]"
                  style="width: 240px"
                  :placeholder="item2.validate ? '必填' : '选填'"
                />
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" v-if="value1">
          <template #default="scope">
            <el-button type="primary" size="small"> 详情 </el-button>
            <el-button
              type="primary"
              size="small"
              @click="delHandle(key1, scope.$index)"
              v-if="scope.row.delabled"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>

    <el-button type="primary" @click="handle">提交</el-button>
  </div>
</template>
<style>
.el-form-item {
  /* margin: 0; */
}
</style>
